﻿using System.Collections.Generic;
using System.Linq;

namespace ccgstore.WebApp.Models
{
    public class PostTree
    {
        public PostNode Root;
        private List<Post> _posts; 

        public PostTree(Thread thread)
        {
            _posts = thread.Posts.OrderByDescending(p => p.CreateDt).ToList();
            var firstPost = _posts.First();

            Root = new PostNode
            {
                Post = firstPost
            };
            _posts.Remove(_posts.First());

            foreach (var post in firstPost.Posts1)
            {
                Root.Children.Add(AddPost(post, Root));
            }
        }

        private PostNode AddPost(Post post, PostNode parent)
        {
            var postNode = new PostNode
            {
                Parent = parent,
                Post = post
            };
            _posts.Remove(post);

            foreach (var childrenPost in post.Posts1)
                postNode.Children.Add(AddPost(childrenPost, postNode));

            return postNode;
        }

        public List<Post> GetOrderedList()
        {
            return PreOrderTraverse(Root, new List<Post>());
        }

        public List<Post> PreOrderTraverse(PostNode postNode, List<Post> postList)
        {
            postList.Add(postNode.Post);

            foreach (var child in postNode.Children)
                postList = PreOrderTraverse(child, postList);

            return postList;
        }
    }
}